#!/bin/sh
# shellcheck shell=dash disable=SC2169 source=/dev/null
#
# Start logging
#

SYSLOGD_ARGS="-n -m 0 -s 0 -b 0 -D"
KLOGD_ARGS="-n"

[[ ! -e /etc/config/syslog ]] && cp /etc/config_templates/syslog /etc/config/
[[ -r /etc/config/syslog ]] && . /etc/config/syslog

if [[ -n "$LOGHOST" ]]; then
  SYSLOGD_ARGS="$SYSLOGD_ARGS -R $LOGHOST -L"
fi

start() {
  echo -n "Starting logging: "
  
  # source all data from /var/hm_mode
  [[ -r /var/hm_mode ]] && . /var/hm_mode

  # make sure /run/systemd/journal exists if running the HomeAssistant add-on
  if [[ -n "${HM_RUNNING_IN_HA}" ]] && [[ ! -d /run/systemd/journal ]]; then
    mkdir -p /run/systemd/journal
  fi

  # shellcheck disable=SC2086
  start-stop-daemon -b -S -q -m -p /var/run/syslogd.pid --exec /sbin/syslogd -- $SYSLOGD_ARGS
  if [[ "${HM_HOST}" != "oci" ]]; then
    # shellcheck disable=SC2086
    start-stop-daemon -b -S -q -m -p /var/run/klogd.pid --exec /sbin/klogd -- $KLOGD_ARGS
  fi
  echo "OK"
}

stop() {
  echo -n "Stopping logging: "
  start-stop-daemon -K -q -p /var/run/syslogd.pid
  start-stop-daemon -K -q -p /var/run/klogd.pid
  echo "OK"
}

case "$1" in
  start)
    start
  ;;
  stop)
    stop
  ;;
  restart|reload)
    stop
    start
  ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac

exit 0
